﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using MusicStore.Domain.POCO;

namespace MusicStore.WebUI
{
    public class ResultSwitcherAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.HttpContext.Request["json"] != null && filterContext.HttpContext.Request["json"] == "true")
            {
                System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                Album album = ((Album)(((ViewResult)filterContext.Result).Model));
                string sJSON = oSerializer.Serialize(new { id = album.AlbumId, title = album.Title, artist = album.Artist.Name});
                
                filterContext.Result = new JsonResult
                {
                    Data = sJSON,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                
                
            }
        }
    }
}